import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useMutation } from '@tanstack/react-query';
import { Button, Form, Input, message, Space } from 'antd';
import { useNavigate } from 'react-router-dom';

import api from '@/apis/api';
import { Messages } from '@/components/Messages/Messages';
import { Logger } from '@/components/useLogger';
import { systemType } from '@/constant/systemType';
import { UsbRegisterRole } from '@/utils/usbKey/register';

import login from '../../img/background1.svg';
import logo1 from '../../img/logo1.png';
import logo2 from '../../img/logo2.png';
import styles from './style.module.less';

const Init = () => {
  // 查询用户数量，若不为空则跳转到登录页面
  const navigate = useNavigate();

  const [form] = Form.useForm();

  const Register = useMutation({
    mutationFn: (params: any) => api.Register(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.open({
          type: 'success',
          content: '注册成功',
        });
        navigate('/login');
      } else {
        message.error(`注册失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.open({
        type: 'error',
        content: '注册失败',
      });
    },
  });

  const handleClickFinish = async (values: any) => {
    let public_key = '';
    if (values.name && values.password) {
      try {
        const publickey = await UsbRegisterRole();
        Logger('public_key', publickey);
        public_key = publickey;
        // localStorage.setItem('isFirstVisit', 'false');
        Messages.success('USBkey注册角色成功！');
        navigate('/login');
      } catch (error: any) {
        Logger(error.message);
        Messages.error('USBkey注册角色失败，请检查USBkey是否插入！');
      }
      Register.mutate({
        username: values.name,
        password: values.password,
        public_key: public_key,
      });
    }
  };

  return (
    <>
      <div className={styles.InitPage}>
        {/* 左边背景 */}
        <div className={styles.Leftdiv}>
          <img
            src={login}
            alt="Login"
            style={{
              width: '50vw',
              height: '100vh',
              objectFit: 'cover',
            }}
          />
        </div>
        {/* 登录盒子 */}
        <div className={styles.InitBox}>
          {/* logo部分 */}
          <div className={styles.Title}>
            <img
              src={systemType === 'school' ? logo1 : logo2}
              alt="Logo"
              className={styles.Logo}
            />
            {systemType === 'school' ? (
              <h1>哈尔滨理工大学 国密服务器密码机</h1>
            ) : (
              <h1>中数国密商用服务器密码机</h1>
            )}
          </div>
          {/* 表单部分 */}
          <div className="form">
            <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
              <Form style={{ width: '100%' }} form={form} onFinish={handleClickFinish}>
                <div>
                  <Form.Item
                    name={'name'}
                    rules={[{ required: true, message: '请输入账号!' }]}
                  >
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="请输入账号"
                      maxLength={30}
                    />
                  </Form.Item>

                  <Form.Item
                    name={'password'}
                    rules={[{ required: true, message: '请输入密码!' }]}
                  >
                    <Input.Password
                      prefix={<LockOutlined />}
                      type="password"
                      placeholder="请输入密码"
                      minLength={4}
                    />
                  </Form.Item>
                  {/* 初始化/登录按钮 */}
                  {/* <div style={{ textAlign: 'right' }}>
                    已有账号?{' '}
                    <a
                      onClick={() => {
                        navigate('/login');
                      }}
                    >
                      点此登录
                    </a>
                  </div> */}
                  <Form.Item>
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'flex-start',
                        gap: '16px',
                        marginTop: '24px',
                      }}
                    >
                      <Button type="primary" htmlType="submit" style={{ width: '450px' }}>
                        初始化超级用户
                      </Button>
                    </div>
                  </Form.Item>
                </div>
              </Form>
            </Space>
          </div>
        </div>
      </div>
    </>
  );
};

export default Init;
